package com.dyzx.hbb.modules.finance.controller;

import cn.hutool.core.bean.BeanUtil;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseCustomController;
import com.dyzx.hbb.common.utils.Utils;
import com.dyzx.hbb.modules.finance.entity.FinanceOrganApproval;
import com.dyzx.hbb.modules.finance.entity.FinanceOrganWallet;
import com.dyzx.hbb.modules.finance.entity.FinanceOrganApproval;
import com.dyzx.hbb.modules.finance.entity.FinanceOrganWalletBill;
import com.dyzx.hbb.modules.finance.query.FinanceOrganApprovalQuery;
import com.dyzx.hbb.modules.finance.service.FinanceOrganApprovalService;
import com.dyzx.hbb.modules.finance.service.FinanceOrganApprovalService;
import com.dyzx.hbb.modules.finance.service.FinanceOrganWalletBillService;
import com.dyzx.hbb.modules.finance.service.FinanceOrganWalletService;
import com.dyzx.hbb.modules.finance.vo.FinanceOrganApprovalVO;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 机构财务审批控制器
 * <p>处理财务系统中机构资金审批相关的操作，包括审批申请、状态更新和资金流转等
 * <p>主要职责：
 * <ul>
 * <li>提供财务审批记录的创建功能</li>
 * <li>支持审批列表查询和详情查询</li>
 * <li>实现审批状态的更新（审核通过/拒绝）</li>
 * <li>处理审批通过后的资金流转逻辑</li>
 * <li>验证账户余额和防止重复提交</li>
 * </ul>
 * <p>设计意图：为财务管理模块提供完整的审批流程支持，
 * 确保资金支出的规范性和可追溯性
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
@RestController
@RequestMapping("/finance/organ_approval")
public class FinanceOrganApprovalController extends BaseCustomController<FinanceOrganApprovalService, FinanceOrganApproval, FinanceOrganApprovalQuery> {
    @Autowired
    private FinanceOrganApprovalService service;
    @Autowired
    private FinanceOrganWalletBillService billService;
    @Autowired
    private FinanceOrganWalletService walletService;

    @PostMapping
    public Result<Boolean> save(@Valid @RequestBody FinanceOrganApprovalVO param) {
        Long userId = SecurityContextHolder.getUserId();
        Long organId = SecurityContextHolder.getOrganId();
        FinanceOrganApproval data = new FinanceOrganApproval();
        BeanUtil.copyProperties(param, data);
        data.setOperatorId(userId);
        data.setOrganId(organId);
        data.setSalesmanId(userId);
        String no = Utils.generateYyMMOrderNumber("FA");
        data.setNo(no);
        boolean save = service.save(data);

        return save ? Result.ok() : Result.error("保存失败");
    }



    @Override
    protected FinanceOrganApprovalService getBaseService() {
        return service;
    }

    @Override
    protected MyLambdaQueryWrapper<FinanceOrganApproval> queryWrapper(FinanceOrganApprovalQuery query) {
        MyLambdaQueryWrapper<FinanceOrganApproval> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(FinanceOrganApproval::getId)
              .select(FinanceOrganApproval::getNo)
                // .select(FinanceOrganApproval::getWalletId)
                // .select(FinanceOrganApproval::getSalesmanId)
                .select(FinanceOrganApproval::getAmount)
                .select("2").as("state")
                .select("(SELECT name FROM finance_category WHERE id = finance_organ_approval.category_id)").as("name")
                .select("(SELECT color FROM finance_category WHERE id = finance_organ_approval.category_id)").as("color")
                .select("(SELECT icon FROM finance_category WHERE id = finance_organ_approval.category_id)").as("icon");
        //  .select(FinanceOrganApproval::getCategoryId);
        queryWrapper.eq(FinanceOrganApproval::getOrganId, SecurityContextHolder.getOrganId());
        if(query!=null){
            queryWrapper.eq(query.getStatus()!=null,FinanceOrganApproval::getStatus, query.getStatus());
        }


        return queryWrapper;
    }

    @Override
    protected MyLambdaQueryWrapper<FinanceOrganApproval> queryInfoWrapper() {
        MyLambdaQueryWrapper<FinanceOrganApproval> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(FinanceOrganApproval::getId)
                .select(FinanceOrganApproval::getNo)
                .select(FinanceOrganApproval::getCreateDate)
                .select(FinanceOrganApproval::getUpdateDate)
                .select(FinanceOrganApproval::getStatus)
                .select(FinanceOrganApproval::getSalesmanId)
                .select(FinanceOrganApproval::getApprovedUserId)
                .select(FinanceOrganApproval::getApprovedDate)
                .select(FinanceOrganApproval::getRemark)
                .select(FinanceOrganApproval::getOperatorId)
                .select(FinanceOrganApproval::getCategoryId)
                .select(FinanceOrganApproval::getImageId)
                .select(FinanceOrganApproval::getExpandedDate)
                .select(FinanceOrganApproval::getRecipientInfo)
                .userName(FinanceOrganApproval::getSalesmanId).as("salesman_name")
                .userName(FinanceOrganApproval::getApprovedUserId).as("approved_user_name")
                .select(FinanceOrganApproval::getAmount)
                .select("2").as("state")
                .imageUrl(FinanceOrganApproval::getImageId).as("image_url")
                .select("(SELECT name FROM finance_category WHERE id = finance_organ_approval.category_id)").as("name")
                .select("(SELECT color FROM finance_category WHERE id = finance_organ_approval.category_id)").as("color")
                .select("(SELECT icon FROM finance_category WHERE id = finance_organ_approval.category_id)").as("icon");
        //  .select(FinanceOrganApproval::getCategoryId);
        queryWrapper.eq(FinanceOrganApproval::getOrganId, SecurityContextHolder.getOrganId());


        return queryWrapper;
    }

    // @ApiOperation(value = "状态")
    @PutMapping("status")
    public Result<Boolean> status(
            @RequestParam(name = "id", defaultValue = "0") long id,
            @RequestParam(name = "status", defaultValue = "0") int status
    ) {
        if (id > 0) {
            if (status > 0) {
                System.out.println("Status:" + status);
                FinanceOrganApproval byId = service.getById(id);
                byId.setStatus(status);
                byId.setApprovedDate(System.currentTimeMillis());
                byId.setApprovedUserId(SecurityContextHolder.getUserId());
                if (status == 1) {
                    boolean validBill2 = billService.validAppervalIdByBill(byId.getId());
                    if (validBill2) {
                     /*   result.setCode(ResultConstant.FAIL);
                        result.setMsg("不能重复提交数据");*/
                        throw new RuntimeException("不能重复提交数据");
                    } else {
                        FinanceOrganWallet validBlance = walletService.validBlance(byId.getAmount());
                        if (validBlance != null) {
                            boolean update = service.updateById(byId);
                            if (update) {


                                FinanceOrganWalletBill bill2 = getBill(byId, validBlance);

                                boolean save = billService.walletBillOut(bill2, validBlance);

                                return save ? Result.ok() : Result.error("提交失败");
                            } else {
                                throw new RuntimeException("提交失败");
                            }
                        } else {
                            //  result.setCode(ResultConstant.FAIL);
                            // result.setMsg("账号余额不足");
                            throw new RuntimeException("账号余额不足");
                        }
                    }
                } else {
                    boolean update = service.updateById(byId);
                    return update ? Result.ok() : Result.error("提交失败");
                }


            } else {
                //  result.setCode(ResultConstant.FAIL);
                return Result.error("参数错误");
            }
        } else {
            //    result.setCode(ResultConstant.EMPTIY);
            return Result.error("参数错误");
        }


    }

    private static FinanceOrganWalletBill getBill(FinanceOrganApproval byId, FinanceOrganWallet validBlance) {
        Long userId = SecurityContextHolder.getUserId();
        Long organId = SecurityContextHolder.getOrganId();
        FinanceOrganWalletBill bill2 = new FinanceOrganWalletBill();
        bill2.setCreateDate(System.currentTimeMillis());
        bill2.setUpdateDate(System.currentTimeMillis());
        bill2.setSalesmanId(byId.getSalesmanId());
        bill2.setAmount(byId.getAmount());
        bill2.setState(2);
        bill2.setCategoryId(byId.getCategoryId());
        bill2.setRemark(byId.getRemark());
        bill2.setImageId(byId.getImageId());
        bill2.setOperatorId(userId);
        bill2.setOrganId(organId);
        bill2.setWalletId(validBlance.getId());
        bill2.setBalanceOld(validBlance.getBalance());
        bill2.setApprovalId(byId.getId());
        String no = Utils.generateYyMMOrderNumber("FB");
        bill2.setNo(no);


        return bill2;
    }
}
